// subpage/pages/mapsearch/mapsearch.js
import { storeBindingsBehavior, createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
const app = getApp();
var util = app.globalData.utils
Page({

  /**
   * 页面的初始数据
   */
  data: {
    map_width: 100,
    map_height: 100,
    detailUserInfo: '',
    basicParams: '',
    keyword: '', //关键词搜索
    stationInfoDispFlag: false, //用于控制站点的显示标志
    distance: '20000', //离自己坐标位置的距离，默认为20Km
    stationList: [],
    lat:'',
    lng:'',
    wmap: {
      centerPoi: { //中心坐标
        longitude: '',
        latitude: '',
      },
      scale: '', //地图的缩放级别
      markers: [], //标记点，用来标记自己所处的位置
    },
    map_width: 100,
    map_height: 100,
    stations: [],
    singel:{},
    name:'',
    basicParams:{
      'appId': 'wxcd7a0c1027942bdc',
      'operatorId': '1',
      'code': '',
      'userPhone': '18512890402',
      'customerId': '1'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      actions: ['updateActives'],
    })
    
    let that = this;
    // let basicParams = JSON.parse(options.basicParams);
    console.log('传输数据',options)
    // 104.078494,30.648986
    if(options.lat){
      that.setData({
        lat: options.lat,
        lng :options.lng 
      })
    }
   
   
   },
     //站点详情
  gosite(event){
    wx.navigateTo({
      url: '/subpage/pages/sitedetail/sitedetail?id='+event.currentTarget.dataset.id,
    })
  },
     //扫码
  userScen() {
    // 允许从相机和相册扫码
    wx.scanCode({
      success(res) {
        console.log(res)
        let sn = res.result;
        let index = sn.lastIndexOf("\=");
        sn = sn.substring(index + 1, sn.length);
        console.log(sn)
        wx.navigateTo({
          url: '/subpage/pages/charge/charge?sn=' + sn,
        })
      }
    })
  },
  getMap(type){
    let that = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log('地图地图',res)
        let markers = that.createMarker(res);
        let centerPoi = {
          longitude: that.data.lng ? that.data.lng:res.longitude,
          latitude: that.data.lat ? that.data.lat : res.latitude
        }
        //构建地图站点标注
        that.buildStation_mapmarkers(that.data.basicParams, markers, centerPoi, type);
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.updateActives(2)
    this.getMap()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  getSearch() {
    this.getMap(true)
  },
  searchValueInput (e){
    this.setData({
      name: e.detail.value
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //创建自己的位置
  createMarker: function (res) {
    //根据中心坐标创建标注
    let latitude = res.latitude;
    let longitude = res.longitude;
    let markers = [];
    var marker = {
      iconPath: '../../images/location.png',
      latitude: latitude,
      longitude: longitude,
      title: '我的位置',
      width: 20,
      height: 20,
      
    }
    markers.push(marker)
    return markers;
  },
  buildStation_mapmarkers: function (basicParams, markers, centerPoi, type) {
    var that = this;
    //参数
    var reqParams = {
        name: that.data.keyword,
        lng: centerPoi.longitude,
        lat: centerPoi.latitude,
        distance: that.data.distance,
        operatorId: basicParams.operatorId,
        customerId: basicParams.customerId,
        name: that.data.name,
       
    }
      let { lng, lat, distance,name } = reqParams
    //参数转换
    // reqParams = util.reqProtocol(reqParams);
    
    //设置站点数据用于以后匹配站点信息
    // that.setData({
    //   stationList: this.data.stations
    // })
    //创建站点标注
    // that.createStationMarker(markers, this.data.stations, centerPoi);

    wx.request({
      url: app.data.url + '/iot/site/all',
      data: { lng, lat, distance,name },
      dataType: 'json',
      method: 'POST',
      success: (res) => {
        console.log('返回数据-------jfjdslj-', res);
        if (res.data.code ==0) {
          //设置站点数据用于以后匹配站点信息
          let list = res.data.list
          list.map(item => {
            if(item.discount) {
              item.discount = (item.discount).toFixed(3)
            }
          })
          that.setData({
            stations: res.data.list
          })
          console.log('请求后数据-----',that.data.stations)
          //创建站点标注
          that.createStationMarker(markers, that.data.stations, centerPoi);
          if(type){
            wx.showToast({
              title: '数据已刷新',
              icon:'none'
            })
          }
        }
      }
    })
  },
  //创建站点的位置
  createStationMarker: function (markers, stations, centerPoi) {
    console.log(stations, ";;;;", centerPoi)
    var that = this;
    //循环遍历stations
    Array.prototype.forEach.call(stations, function (n, i, item) {
      // console.log('遍历的站点列表信息', n)
      var latitude = n.lat;
      var longitude = n.lng;
      var _gcj02 = util.bd09Togcj02(longitude, latitude);
      // console.log('_gcj02', _gcj02)
      let iconPath = n.free >= 0 ? '../../images/map_marker.png' : '../../images/icon_markb.png';
      markers.push({
        name:n.name,
        pileNum:n.pileNum,
        discount:n.discount,
        free:n.free,
        id: parseInt(n.id),
        latitude: n.lat,
        longitude: n.lng,
        iconPath: iconPath,
        width: n.free > 0 ? 47 : 34,
        height: n.free > 0 ? 47 : 34,
        customCallout: {
          anchorX: 0,
          anchorY: 0,
          display: 'ALWAYS'
          }
      })
    })
    console.log('markers', markers)
    that.setData({
      wmap: {
        centerPoi: centerPoi,
        scale: 13,
        markers: markers
      }
    })
  },
  //站点详情
  markerClick: function (e) {
    //站点id
    console.log('显示单项站点详情', e)
    let siteId = e.detail.markerId;
    let stationList = this.data.stations;
    let station = {};
    for (var i = 0; i < stationList.length; i++) {
      if (Number(stationList[i].id) == Number(siteId)) {
        station = stationList[i];
        break;
      }
    }
    console.log('sssss',station)
    this.setData({
      singel: station,
      stationInfoDispFlag: true,
      // map_height: 50
    })
    console.log(station)
  },
  mapClick: function () {
    this.setData({
      // stationInfoDispFlag: false,
      // map_height: 100
    })
  },
  //charging_btn 去充电
  charging_btn(e) {
    console.log('去充电', e)
    wx.navigateTo({
      url: '/subpage/pages/charge/charge',
    })
  },
  //导航
  navi_btn: function (e) {
    console.log('导航',e)
    let lng = e.currentTarget.dataset.lng;
    let lat = e.currentTarget.dataset.lat;
    let address = e.currentTarget.dataset.address;
    var _gcjo2 = util.bd09Togcj02(lng, lat);
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        wx.openLocation({
          latitude: Number(lat),
          longitude: Number(lng),
          name: address,
          scale: 16, //缩放比例为18
        })
      },
    })
  },
})